/**
 * Area
 * 
 * Public/js/backend/area.js
 * admin @ 2015-06-11
 */

var Area = {
  config: {
    
  },
  init : function( config ){
    var _this = this ;
    $.extend( _this.config , config );
    
    _this.init_select();
    var url = _this.config.get_default_url ;
    $.get( url , function(ret){      
      _this.make_option('province' , ret.province , ret.province_id );
      _this.make_option('city' , ret.city , ret.city_id );
      _this.make_option('district' , ret.district , ret.district_id );
    });
  },
  
  init_select : function() {
    var _this = this ;
    
    //省份改变
    $(document).on('change', '#province', function (e) {
      var pid = $(this).val();
      var url = _this.config.get_by_pid_url + '/' + pid ;
      $.get( url , function(ret){
        _this.make_option('city' , ret.data , ret.default_id );
        var d_url = _this.config.get_by_pid_url + '/' + ret.default_id ;
        $.get( d_url ,  function(ret){
          _this.make_option('district' , ret.data , ret.default_id );
        });
      });
    });
    
    //城市改变
    $(document).on('change', '#city', function (e) {
      var pid = $(this).val();
      var url = _this.config.get_by_pid_url + '/' + pid ;
      $.get( url , function(ret){
        _this.make_option('district' , ret.data , ret.default_id );
      });
    });
  }, 
  
  //生成option
  make_option : function( type , data , default_id  ) {
    var html = '';
    for( var i = 0 ; i < data.length ; i++ ) {
      html += '<option value="'+ data[i]['id'] +'">'+ data[i]['text'] +'</option>';
    }
    $('#'+type).empty().append(html).val(default_id); 
  },
  
  make_by_area : function(district_id) {
    var _this = this ;
    var url = _this.config.get_by_district_url + '/' + district_id ;
    $.get( url , function(ret){
      _this.make_option('province' , ret.province , ret.province_id );
      _this.make_option('city' , ret.city , ret.city_id );
      _this.make_option('district' , ret.district , ret.district_id );
    });
    
  }
}






